package arr.除自身以外数组的乘积;

public class Solution {

    /**
     * 设置两个数组前缀乘积 prefixProduct[] 后缀乘积 suffixProduct[]
     * answer[i] = prefixProduct[i-1] * suffixProduct[i+1]
     */
    public int[] productExceptSelf(int[] nums) {
        int len = nums.length;
        int[] ans = new int[len];
        int[] prefixProduct = new int[len];
        int[] suffixProduct = new int[len];
        prefixProduct[0] = nums[0];
        suffixProduct[len - 1] = nums[len - 1];
        for (int i = 1; i < len; i++) {
            prefixProduct[i] = nums[i] * prefixProduct[i - 1];
            suffixProduct[len - 1 - i] = nums[len - i - 1] * suffixProduct[len - i];
        }
        ans[0] = suffixProduct[1];
        ans[len - 1] = prefixProduct[len - 2];
        for (int i = 1; i < len - 1; i++) {
            ans[i] = prefixProduct[i - 1] * suffixProduct[i + 1];
        }
        return ans;
    }

    public static void main(String[] args) {
        int[] a = new int[]{1, 2, 3, 4};
        Solution solution = new Solution();
        solution.productExceptSelf(a);
    }

}
